package com.google.gwt.sample.dynatablerf.client.widgets;

import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.view.client.SelectionModel;

public class GrifoCheckBoxColumnHeader<T> extends Header<Boolean> {

	private DataGrid<T> dataGrid;
	private SelectionModel<T> selectionModel;

	public GrifoCheckBoxColumnHeader(DataGrid<T> dataGrid,
			SelectionModel<T> selectionModel) {
		super(new CheckboxCell());
		this.dataGrid = dataGrid;
		this.selectionModel = selectionModel;
	}

	@Override
	public Boolean getValue() {
		for (T item : dataGrid.getVisibleItems()) {
			if (!selectionModel.isSelected(item)) {
				return true;
			}
		}
		return dataGrid.getVisibleItems().isEmpty();
	}

	@Override
	public void onBrowserEvent(Context context, Element elem, NativeEvent event) {
		InputElement input = elem.getFirstChild().cast();
		Boolean isChecked = input.isChecked();
		for (T element : dataGrid.getVisibleItems()) {
			selectionModel.setSelected(element, !isChecked);
		}
	}
}